<template>
	<view class="ksp-editor">
		<view class="body">
			<view class="content">
				<view class="node" v-for="(node, index) in nodes" :key="node.id">
					<textarea auto-focus="true" @blur="textBlur($event, index)" @input="textChange($event, node)"
						class="text" auto-height="true" maxlength="-1" v-if="node.type == 'text'" :cursor="node.cursor"
						:value="node.content" v-model="node.content"></textarea>
					<image @load="imageLoad($event, node)" class="image"
						:style="{width: node.width, height: node.height}" v-if="node.type == 'image'" :src="node.url">
					</image>
					<image @tap="deleteImage($event, node, index)" class="btn-delete" v-if="node.type == 'image'"
						src="">
					</image>
				</view>
			</view>
		</view>
		<view class="toolbar">
			<view @tap="selectImage" class="btn-img">
				<uni-icons type="image" color="$mk-base-color" size="35"></uni-icons>
			</view>
			<!-- <button @tap="save" class="btn-save" @click="submit">保存</button> -->
			<view class="btn-save" @click="submit">发布</view> >
		</view>
	</view>
	</view>
</template>

<script>
	export default {
		props: {
			list: {
				default: null
			},
		},
		data() {
			return {
				//分类
			
				array: ['文章分类', 'Java', '架构', '前端开发', '后端开发', '移动开发', '大数据', '其他'],
				index: 0,
				//
				content:'',
				articleTit:' ',
				sequence: 0,
				selection: {
					index: 0,
					cursor: 0
				},
				nodes: [],
				// url: "http://ehome-totem.img-cn-shenzhen.aliyuncs.com/1912021526894820202354639.png"
			};
		},
		mounted() {
			this.initNodes();
		},
		methods: {
			//选择器
			bindPickerChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.index = e.detail.value
			},
			bindDateChange: function(e) {
				this.date = e.detail.value
			},

			obtainSequence() {
				this.sequence++;
				return this.sequence;
			},
			initNodes() {
				var list = this.list || [];
				if (Object.prototype.toString.call(list) != "[object Array]") {
					throw new Error("数据格式不正确！")
				}
				var nodes = [];
				for (var i = 0; i < list.length; i++) {
					var ele = list[i];
					if (ele.type == "text") {
						var node = {};
						node.type = "text";
						node.id = this.obtainSequence();
						node.content = ele.content || "";
						nodes.push(node);
					} else if (ele.type == "image") {
						var node = {};
						node.type = "image";
						node.id = this.obtainSequence();
						node.width = "100px";
						node.height = "100px";
						node.url = ele.url || "";
						nodes.push(node);
					}
				}
				this.nodes = nodes;
				this.trimNodes();
			},
			trimNodes() {
				var list = this.nodes;
				var nodes = [];
				var temp = null;
				for (var i = 0; i < list.length; i++) {
					var node = list[i];
					if (node.type == "image") {
						nodes.push(node);
						temp = null;
						continue;
					}
					if (!temp) {
						temp = node;
						nodes.push(temp);
						continue;
					}
					if (node.type == "text") {
						temp.content += node.content;
					}
				}
				if (nodes.length == 0 || nodes[nodes.length - 1].type != "text") {
					var node = {};
					node.id = this.obtainSequence();
					node.type = "text";
					node.content = "";
					nodes.push(node);
				}
				this.nodes = nodes;
			},
			imageLoad(ev, node) {
				var query = uni.createSelectorQuery().in(this);
				query.select(".content").boundingClientRect((data) => {
					var cw = data.width;
					var iw = ev.detail.width;
					var ih = ev.detail.height;
					node.width = cw + "px";
					node.height = ih / iw * cw + "px";
				}).exec();
			},
			textChange(ev, node) {
				node.content = ev.detail.value;
				setTimeout(() => {
					node.cursor = 1;
				}, 500)
			},
			textBlur(ev, index) {
				this.selection.index = index;
				this.selection.cursor = ev.detail.cursor;
			},
			selectImage() {
				this.$emit("selectImage");
			},
			addImage(url) {
				var index = this.selection.index;
				var cursor = this.selection.cursor;
				var snode = this.nodes[index];
				var content = snode.content;
				if (cursor == 0) {} else if (cursor < content.length) {
					snode.content = content.substring(0, cursor);
					var node = {};
					node.id = this.obtainSequence();
					node.type = "text";
					node.content = content.substring(cursor);
					this.nodes.splice(index + 1, 0, node);
					index++;
				} else {
					index++;
				}
				var node = {};
				node.id = this.obtainSequence();
				node.type = "image";
				node.url = url;
				node.width = "100px";
				node.height = "100px";
				this.nodes.splice(index, 0, node);
				this.trimNodes();
			},
			deleteImage(ev, node, index) {
				uni.showModal({
					content: '你确定删除吗？',
					success: (res) => {
						if (!res.confirm) {
							return;
						}
						this.nodes.splice(index, 1);
						if (this.selection.index > index) {
							this.selection.index--;
						}
						this.trimNodes();
						var url = node.url;
						this.$emit("deleteImage", {
							url: url
						});
					}
				});
			},
			//保存
			// 		save() {
			// 			var result = [];
			// 			for (var i = 0; i < this.nodes.length; i++) {
			// 				var node = this.nodes[i];
			// 				var ele = {};
			// 				ele.type = node.type;
			// 				if (node.type == "text") {
			// 					ele.content = node.content;
			// 				} else if (node.type == "image") {
			// 					ele.url = node.url;
			// 				}
			// 				result.push(ele);
			// 			}
			// 			this.$emit("save", {
			// 				result: result
			// 			});

			// 		},
			async submit() {
				var result = [];
				uni.showLoading({

				})
				for (var i = 0; i < this.nodes.length; i++) {
					var node = this.nodes[i];
					var ele = {};
					ele.type = node.type;
					if (node.type == "text") {
						ele.content = node.content;
					} else if (node.type == "image") {
						ele.url = node.url;
						// 
						await this.uploadFiles(this.nodes[i].url)
					}
					result.push(ele);
				}
				this.uploadPassage({
					title:result[0].content,
					content:result
				})
					console.log(result)


			},
			async uploadFiles(filePath) {
				const resultt = await uniCloud.uploadFile({
					// 上传路径
					filePath: filePath,
					cloudPath: "file",
				})
				console.log(resultt);
				return resultt.fileID
			},
			//调用云函数
			uploadPassage({title,content}){
				this.$api.uploadPassage({title,content}).then(res=>{
					//处理完成
					uni.hideLoading()
					uni.showToast({
						icon:"none",
						title:"文章上传成功"
					})
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/tabbar/follow/follow'
						})
					}, 2000)
				}).catch(()=>{
					uni.showToast({
						icon:"none",
						title:"文章上传失败"
					})
				})
			}


		},



		watch: {
			"list": function() {
				this.initNodes();
			}
		}
	}
</script>

<style lang="scss">
	.ksp-editor {
		position: absolute;
		width: 100%;
		height: 100%;
		left: 0upx;
		top: 1%;

		/* background-color: #f5f5f5; */
		/* border: 2px red solid; */
		.body {
			position: absolute;
			left: 0upx;
			right: 0upx;
			top: 0%;
			bottom: 100upx;
			background: white;

			.content {
				position: absolute;
				left: 20upx;
				right: 20upx;
				top: 10%;
				// margin: 10px 0px;
				// padding: 4px;
				bottom: 20upx;
				overflow-y: auto;

				.node {
					.passageTitle {
						font-size: 50rpx;
						background-color: rosybrown;
						padding-left: 4%;
						color: #c58545;
						font-weight: 800;
					}

					.btn-delete {
						position: absolute;
						right: 20rpx;
						top: 60rpx;
						width: 20px;
						height: 20px;
					}

					.classify {
						width: 100%;
						float: right;
						position: absolute;
						top: 4%;
						right: 0;
						margin-left: 6%;
						flex-direction: row-reverse;
						line-height: 30px;
						display: block;
						font-size: 15px;
						justify-content: space-between;
						align-items: center;
						height: 30px;
						color: #878787;

						// border: 3px saddlebrown solid;
						.uni-list {
							// background: #969696;
						}
					}
				}
			}

		}
	}

	.toolbar {
		// position: fixed;
		width: 100%;
		height: 100px;
		left: 0upx;
		bottom: 0upx;
		align-items: center;
		box-sizing: border-box;
		border-top: 1px solid #ffffff;
		background: #ffffff;

		/* border: 2px dodgerblue solid; */
		.btn-img {
			position: fixed;
			/* text-align: center; */
			// line-height: 30px;
			padding: 10px;
			// width: 60px;
			// height: 10px;
			left: 30upx;
			bottom:30upx;
			align-items: center;
			// height: 50px; 
			// background-color: red;
			border-radius: 50%;
			// border: 2px red solid;
			box-shadow: 6px 6px 10px rgb(235, 235, 235);

		}


		.btn-save {
		position: fixed;
		right: 4%;
		width: 60px;
		top: 4%;
		text-align: center;
		color: $mk-base-color;
		font-size: 16px;
		font-weight: 400;
		height: 25px;
		border-radius: 30px;
		padding-top: 4px;
		// background: $mk-base-color;
		// box-shadow: #b9b9b9 2px;
		z-index: 90;
		box-shadow: 4px 4px 10px rgb(227, 227, 227);
		
					}
	}
</style>
